package com.novix.utility.log;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;

import java.util.Properties;

import org.apache.log4j.helpers.LogLog;

import org.apache.log4j.net.SMTPAppender;
import org.apache.log4j.spi.ErrorCode;

public class AuthSMTPAppender extends SMTPAppender {

	/**
	 * SimpleAuthenticator is used to do simple authentication when the SMTP
	 * server requires it. It pulls the username and password from
	 * log4j.properties or where appropriate.
	 */
	private class SMTPAuthenticator extends javax.mail.Authenticator {

		public PasswordAuthentication getPasswordAuthentication() {

			String username = _user;
			String password = _password;
			return new PasswordAuthentication(username, password);
		}
	}

	private String _user;
	private String _password;

	public String getUser() {
		return _user;
	}
	public void setUser(String user) {
		_user = user;
	}

	public String getPassword() {
		return _password;
	}
	public void setPassword(String password) {
		_password = password;
	}

	/**
	 * Overrode activeOptions() to have authentication
	 */
	public void activateOptions() {
		Properties props = new Properties(System.getProperties());
		if (getSMTPHost() != null) {
			props.put("mail.smtp.host", getSMTPHost());
		}

		// New authentication bit
		props.put("mail.smtp.auth", "true");
		Authenticator auth = new SMTPAuthenticator();
		Session session = Session.getInstance(props, auth);
		// Session session = Session.getInstance(props, null);

		// session.setDebug(true);
		msg = new MimeMessage(session);

		try {
			if (getFrom() != null) {
				msg.setFrom(getAddress(getFrom()));
			} else {
				msg.setFrom();
			}

			msg.setRecipients(Message.RecipientType.TO, parseAddress(getTo()));
			if (getSubject() != null) {
				msg.setSubject(getSubject());
			}
		} catch (MessagingException e) {
			LogLog.error("Could not activate SMTPAppender options.", e);
		}
	}
	InternetAddress getAddress(String addressStr) {
		try {
			return new InternetAddress(addressStr);
		} catch (AddressException e) {
			errorHandler.error("Could not parse address [" + addressStr + "].",
					e, ErrorCode.ADDRESS_PARSE_FAILURE);
			return null;
		}
	}
	InternetAddress[] parseAddress(String addressStr) {
		try {
			return InternetAddress.parse(addressStr, true);
		} catch (AddressException e) {
			errorHandler.error("Could not parse address [" + addressStr + "].",
					e, ErrorCode.ADDRESS_PARSE_FAILURE);
			return null;
		}
	}
}
